# Self-querying

A self-querying retriever is one that, as the name suggests, has the ability to query itself. Specifically, given any natural language query, the retriever uses a query-constructing LLM chain to write a structured query and then applies that structured query to it's underlying VectorStore. This allows the retriever to not only use the user-input query for semantic similarity comparison with the contents of stored documented, but to also extract filters from the user query on the metadata of stored documents and to execute those filters.

![](https://drive.google.com/uc?id=1OQUN-0MJcDUxmPXofgS7MqReEs720pqS)

All Self Query retrievers require `peggy` as a peer dependency:

import Tabs from "@theme/Tabs";
import TabItem from "@theme/TabItem";
import CodeBlock from "@theme/CodeBlock";

<Tabs>
  <TabItem value="npm" label="npm" default>
    <CodeBlock language="bash">npm install -S peggy</CodeBlock>
  </TabItem>
  <TabItem value="yarn" label="Yarn">
    <CodeBlock language="bash">yarn add peggy</CodeBlock>
  </TabItem>
  <TabItem value="pnpm" label="pnpm">
    <CodeBlock language="bash">pnpm add peggy</CodeBlock>
  </TabItem>
</Tabs>

## Usage

Here's a basic example with an in-memory, unoptimized vector store:

import Example from "@examples/retrievers/memory_self_query.ts";

import IntegrationInstallTooltip from "@mdx_components/integration_install_tooltip.mdx";

<IntegrationInstallTooltip></IntegrationInstallTooltip>

```bash npm2yarn
npm install @langchain/openai
```

<CodeBlock language="typescript">{Example}</CodeBlock>

## Setting default search params

You can also pass in a default filter when initializing the self-query retriever that will be used in combination
with or as a fallback to the generated query. For example, if you wanted to ensure that your query documents tagged as `genre: "animated"`,
you could initialize the above retriever as follows:

```typescript
const selfQueryRetriever = await SelfQueryRetriever.fromLLM({
  llm,
  vectorStore,
  documentContents,
  attributeInfo,
  structuredQueryTranslator: new FunctionalTranslator(),
  searchParams: {
    filter: (doc: Document) =>
      doc.metadata && doc.metadata.genre === "animated",
    mergeFiltersOperator: "and",
  },
});
```

The type of filter required will depend on the specific translator used for the retriever. See the individual pages for examples.

Other supported values for `mergeFiltersOperator` are `"or"` or `"replace"`.
